<template>
  <div class="card-list">
    <el-card class="card-card">
      <template #header>
        <div class="card-header">
          <span>会员卡列表</span>
          <div class="header-actions">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option label="未激活" :value="0" />
              <el-option label="正常" :value="1" />
              <el-option label="冻结" :value="2" />
              <el-option label="过期" :value="3" />
              <el-option label="注销" :value="4" />
            </el-select>
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入会员姓名或卡号"
              style="width: 300px; margin-right: 10px"
              clearable
              :maxlength="200"
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">办理会员卡</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="cardList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="cardNumber" label="卡号" width="150" />
        <el-table-column prop="memberName" label="会员姓名" width="120" />
        <el-table-column prop="cardTypeName" label="卡类型" width="120" />
        <el-table-column prop="balance" label="余额(元)" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="activationDate" label="激活日期" width="120" />
        <el-table-column prop="expiryDate" label="到期日期" width="120" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="primary"
              @click="handleActivate(scope.row)"
            >
              激活
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="warning"
              @click="handleFreeze(scope.row)"
            >
              冻结
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              size="small"
              type="success"
              @click="handleUnfreeze(scope.row)"
            >
              解冻
            </el-button>
            <el-button
              v-if="scope.row.status === 1 || scope.row.status === 2"
              size="small"
              @click="handleRecharge(scope.row)"
            >
              充值
            </el-button>
            <el-button
              v-if="scope.row.status === 1 || scope.row.status === 2"
              size="small"
              @click="handleConsume(scope.row)"
            >
              消费
            </el-button>
            <el-button
              v-if="scope.row.status === 1 || scope.row.status === 2"
              size="small"
              type="danger"
              @click="handleCancel(scope.row)"
            >
              注销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 办理会员卡对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="办理会员卡"
      width="500px"
    >
      <el-form
        ref="addCardFormRef"
        :model="addCardForm"
        :rules="addCardRules"
        label-width="100px"
      >
        <el-form-item label="会员" prop="memberId">
          <el-select
            v-model="addCardForm.memberId"
            placeholder="请选择会员"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="member in memberList"
              :key="member.id"
              :label="`${member.name} (${member.phone})`"
              :value="member.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="卡类型" prop="cardTypeId">
          <el-select
            v-model="addCardForm.cardTypeId"
            placeholder="请选择卡类型"
            style="width: 100%"
            @change="handleCardTypeChange"
          >
            <el-option
              v-for="cardType in cardTypeList"
              :key="cardType.id"
              :label="cardType.name"
              :value="cardType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="初始余额" prop="balance">
          <el-input-number
            v-model="addCardForm.balance"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="激活日期" prop="activationDate">
          <el-date-picker
            v-model="addCardForm.activationDate"
            type="date"
            placeholder="请选择激活日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="到期日期" prop="expiryDate">
          <el-date-picker
            v-model="addCardForm.expiryDate"
            type="date"
            placeholder="请选择到期日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSave" :loading="addLoading">办理</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog
      v-model="rechargeDialogVisible"
      title="充值"
      width="400px"
    >
      <el-form
        ref="rechargeFormRef"
        :model="rechargeForm"
        :rules="rechargeRules"
        label-width="80px"
      >
        <el-form-item label="卡号">
          <el-input v-model="currentCard.cardNumber" disabled />
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="currentCard.balance" disabled />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number
            v-model="rechargeForm.amount"
            :min="0.01"
            :step="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="rechargeForm.paymentMethod" style="width: 100%">
            <el-option label="现金" value="cash" />
            <el-option label="银行卡" value="bank" />
            <el-option label="微信" value="wechat" />
            <el-option label="支付宝" value="alipay" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRechargeSave" :loading="rechargeLoading">充值</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 消费对话框 -->
    <el-dialog
      v-model="consumeDialogVisible"
      title="消费"
      width="400px"
    >
      <el-form
        ref="consumeFormRef"
        :model="consumeForm"
        :rules="consumeRules"
        label-width="80px"
      >
        <el-form-item label="卡号">
          <el-input v-model="currentCard.cardNumber" disabled />
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="currentCard.balance" disabled />
        </el-form-item>
        <el-form-item label="消费金额" prop="amount">
          <el-input-number
            v-model="consumeForm.amount"
            :min="0.01"
            :max="currentCard.balance"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="消费描述" prop="description">
          <el-input
            v-model="consumeForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入消费描述"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="consumeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConsumeSave" :loading="consumeLoading">消费</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Member } from '@/types/api/member'
import type { CardType, MembershipCard as Card, CreateCardRequest, RechargeRequest, ConsumeRequest } from '@/types/api/card'
import { cardApi } from '@/api/modules/card'
import { memberApi } from '@/api/modules/member'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const cardList = ref<Card[]>([])
const searchForm = reactive({
  keyword: '',
  status: undefined as number | undefined
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addCardFormRef = ref()

const rechargeDialogVisible = ref(false)
const rechargeLoading = ref(false)
const rechargeFormRef = ref()

const consumeDialogVisible = ref(false)
const consumeLoading = ref(false)
const consumeFormRef = ref()

const freezeDialogVisible = ref(false)
const freezeLoading = ref(false)
const freezeFormRef = ref()

// 下拉列表数据
const memberList = ref<Member[]>([])
const cardTypeList = ref<CardType[]>([])

// 当前操作的会员卡
const currentCard = ref<Card>({
  id: 0,
  cardNumber: '',
  memberId: 0,
  memberName: '',
  cardTypeId: 0,
  cardTypeName: '',
  balance: 0,
  status: 0,
  activationDate: '',
  expiryDate: '',
  createdAt: '',
  updatedAt: ''
})

// 表单数据
const addCardForm = reactive({
  memberId: undefined as number | undefined,
  cardTypeId: undefined as number | undefined,
  balance: 0,
  activationDate: '',
  expiryDate: ''
})

const rechargeForm = reactive({
  cardId: 0,
  amount: 0,
  paymentMethod: 'cash'
})

const consumeForm = reactive({
  cardId: 0,
  amount: 0,
  description: ''
})

const freezeForm = reactive({
  cardId: 0,
  isFrozen: false,
  reason: ''
})

// 表单验证规则
const addCardRules = {
  memberId: [
    { required: true, message: '请选择会员', trigger: 'change' }
  ],
  cardTypeId: [
    { required: true, message: '请选择卡类型', trigger: 'change' }
  ],
  activationDate: [
    { required: true, message: '请选择激活日期', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择到期日期', trigger: 'change' }
  ]
}

const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

const consumeRules = {
  amount: [
    { required: true, message: '请输入消费金额', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入消费描述', trigger: 'blur' }
  ]
}

const freezeRules = {
  reason: [
    { required: true, message: '请输入原因', trigger: 'blur' }
  ]
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch (status) {
    case 0: return 'info'    // 未激活
    case 1: return 'success' // 正常
    case 2: return 'warning' // 冻结
    case 3: return 'danger'  // 过期
    case 4: return 'danger'  // 注销
    default: return 'info'
  }
}

// 格式化状态显示
const formatStatus = (status: number) => {
  switch (status) {
    case 0: return '未激活'
    case 1: return '正常'
    case 2: return '冻结'
    case 3: return '过期'
    case 4: return '注销'
    default: return '未知'
  }
}

// 获取会员卡列表
const getCardList = async () => {
  loading.value = true
  try {
    const response = await cardApi.getCardList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status
    })
    cardList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取会员卡列表失败')
  } finally {
    loading.value = false
  }
}

// 获取会员列表
const getMemberList = async () => {
  try {
    const response = await memberApi.getMemberList({
      page: 1,
      pageSize: 1000 // 获取所有会员
    })
    memberList.value = response.data.data.list
  } catch (error) {
    ElMessage.error('获取会员列表失败')
  }
}

// 获取卡类型列表
const getCardTypeList = async () => {
  try {
    const response = await cardApi.getCardTypeList({
      page: 1,
      pageSize: 1000 // 获取所有卡类型
    })
    cardTypeList.value = response.data.data.list
  } catch (error) {
    ElMessage.error('获取卡类型列表失败')
  }
}

// 卡类型选择改变时
const handleCardTypeChange = (cardTypeId: number) => {
  const cardType = cardTypeList.value.find(ct => ct.id === cardTypeId)
  if (cardType) {
    // 设置默认到期日期为激活日期加上有效期
    const activationDate = new Date(addCardForm.activationDate)
    if (!isNaN(activationDate.getTime())) {
      const expiryDate = new Date(activationDate)
      expiryDate.setDate(expiryDate.getDate() + cardType.validityPeriod)
      addCardForm.expiryDate = expiryDate.toISOString().split('T')[0] || ''
    }
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getCardList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getCardList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getCardList()
}

// 办理会员卡
const handleAdd = () => {
  addDialogVisible.value = true
  // 重置表单
  Object.assign(addCardForm, {
    memberId: undefined,
    cardTypeId: undefined,
    balance: 0,
    activationDate: new Date().toISOString().split('T')[0],
    expiryDate: ''
  })
  // 获取下拉列表数据
  getMemberList()
  getCardTypeList()
}

// 查看会员卡详情
const handleView = (row: Card) => {
  ElMessage.info('查看会员卡详情功能待实现')
}

// 激活会员卡
const handleActivate = (row: Card) => {
  formUtils.handleDeleteConfirm(`会员卡 "${row.cardNumber}"`, async () => {
    await cardApi.activateCard(row.id)
    getCardList()
  }, {
    title: '激活会员卡',
    successMessage: '激活成功',
    errorMessage: '激活失败'
  })
}

// 冻结会员卡
const handleFreeze = (row: Card) => {
  formUtils.handleDeleteConfirm(`会员卡 "${row.cardNumber}"`, async () => {
    await cardApi.freezeCard(row.id)
    getCardList()
  }, {
    title: '冻结会员卡',
    successMessage: '冻结成功',
    errorMessage: '冻结失败'
  })
}

// 解冻会员卡
const handleUnfreeze = (row: Card) => {
  formUtils.handleDeleteConfirm(`会员卡 "${row.cardNumber}"`, async () => {
    await cardApi.unfreezeCard(row.id)
    getCardList()
  }, {
    title: '解冻会员卡',
    successMessage: '解冻成功',
    errorMessage: '解冻失败'
  })
}

// 注销会员卡
const handleCancel = (row: Card) => {
  formUtils.handleDeleteConfirm(`会员卡 "${row.cardNumber}"`, async () => {
    await cardApi.cancelCard(row.id)
    getCardList()
  }, {
    title: '注销会员卡',
    successMessage: '注销成功',
    errorMessage: '注销失败'
  })
}

// 充值
const handleRecharge = (row: Card) => {
  currentCard.value = { ...row }
  rechargeDialogVisible.value = true
  // 重置表单
  Object.assign(rechargeForm, {
    cardId: row.id,
    amount: 0,
    paymentMethod: 'cash'
  })
}

// 消费
const handleConsume = (row: Card) => {
  currentCard.value = { ...row }
  consumeDialogVisible.value = true
  // 重置表单
  Object.assign(consumeForm, {
    cardId: row.id,
    amount: 0,
    description: ''
  })
}

// 保存办理会员卡信息
const handleAddSave = async () => {
  if (!addCardFormRef.value) return

  await addCardFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      await preventDuplicateSubmit('create_card', async () => {
        addLoading.value = true
        try {
          const createData: CreateCardRequest = {
            memberId: addCardForm.memberId!,
            cardTypeId: addCardForm.cardTypeId!,
            balance: addCardForm.balance,
            activationDate: addCardForm.activationDate,
            expiryDate: addCardForm.expiryDate
          }
          await cardApi.createCard(createData)
          ElMessage.success('办理成功')
          addDialogVisible.value = false
          getCardList()
        } catch (error: any) {
          ElMessage.error('办理失败')
          throw error // 重新抛出错误以确保防重复提交正确处理
        } finally {
          addLoading.value = false
        }
      })
    }
  })
}

// 保存充值信息
const handleRechargeSave = async () => {
  if (!rechargeFormRef.value) return

  await rechargeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      await preventDuplicateSubmit(`recharge_card_${rechargeForm.cardId}`, async () => {
        rechargeLoading.value = true
        try {
          const rechargeData: RechargeRequest = {
            cardId: rechargeForm.cardId,
            amount: rechargeForm.amount,
            paymentMethod: rechargeForm.paymentMethod
          }
          await cardApi.recharge(rechargeData)
          ElMessage.success('充值成功')
          rechargeDialogVisible.value = false
          getCardList()
        } catch (error: any) {
          ElMessage.error('充值失败')
          throw error // 重新抛出错误以确保防重复提交正确处理
        } finally {
          rechargeLoading.value = false
        }
      })
    }
  })
}

// 保存消费信息
const handleConsumeSave = async () => {
  if (!consumeFormRef.value) return

  await consumeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      await preventDuplicateSubmit(`consume_card_${consumeForm.cardId}`, async () => {
        consumeLoading.value = true
        try {
          const consumeData: ConsumeRequest = {
            cardId: consumeForm.cardId,
            amount: consumeForm.amount,
            description: consumeForm.description
          }
          await cardApi.consume(consumeData)
          ElMessage.success('消费成功')
          consumeDialogVisible.value = false
          getCardList()
        } catch (error: any) {
          ElMessage.error('消费失败')
          throw error // 重新抛出错误以确保防重复提交正确处理
        } finally {
          consumeLoading.value = false
        }
      })
    }
  })
}

// 保存冻结/解冻信息
const handleFreezeSave = async () => {
  if (!freezeFormRef.value) return

  await freezeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      await preventDuplicateSubmit(`freeze_card_${freezeForm.cardId}`, async () => {
        freezeLoading.value = true
        try {
          if (freezeForm.isFrozen) {
            // 冻结会员卡
            await cardApi.freezeCard(freezeForm.cardId)
          } else {
            // 解冻会员卡
            await cardApi.unfreezeCard(freezeForm.cardId)
          }
          ElMessage.success(`${freezeForm.isFrozen ? '冻结' : '解冻'}成功`)
          freezeDialogVisible.value = false
          getCardList()
        } catch (error: any) {
          ElMessage.error(`${freezeForm.isFrozen ? '冻结' : '解冻'}失败`)
          throw error // 重新抛出错误以确保防重复提交正确处理
        } finally {
          freezeLoading.value = false
        }
      })
    }
  })
}

// 初始化
onMounted(() => {
  getCardList()
})
</script>

<style scoped lang="scss">
.card-list {
  .card-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
